//
//  ProductListViewController.m
//  Finance
//
//  Created by cheng xiang on 13-4-2.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "ProductListViewController.h"
#import "AppDelegate.h"
#import "ProductDetailView.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
#import "ProductListCell.h"
#import "NearbyDetailViewController.h"
#import "WEPopoverContentViewController.h"
#import "UIBarButtonItem+WEPopover.h"
#import "FilterViewController.h"

@interface ProductListViewController ()
- (NSDictionary *)PackageBody:(int)index;
@end

@implementation ProductListViewController

@synthesize tableView = _tableView, reloading = _reloading, loadFooterView = _loadFooterView;
@synthesize dataArray = _dataArray, currentOffsetPoint = _currentOffsetPoint, pageIndex = _pageIndex;
@synthesize popController = _popController;
@synthesize type = _type, refreshTableView = _refreshTableView, sortDic = _sortDic,headerView = _headerView;
@synthesize backdiect=_backdiect;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)getSearch
{
    self.navigationController.toolbarHidden = NO;
    [self setHidesBottomBarWhenPushed:YES];
    FilterViewController *aController = [[FilterViewController alloc] init];
    [self.navigationController pushViewController:aController animated:YES];
}

/*
- (void)getFilter:(id)sender
{
    if (!self.popController) {
		
		UIViewController *contentViewController = [[WEPopoverContentViewController alloc] initWithStyle:UITableViewStylePlain];
		self.popController = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
		self.popController.delegate = self;
        //添加不响应dismiss操作的views
		//self.popController.passthroughViews = [NSArray arrayWithObject:self.toolBar];
		
		[self.popController presentPopoverFromBarButtonItem:[self.toolBar.items objectAtIndex:0]
									   permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown)
													   animated:YES];
        
	} else {
		[self.popController dismissPopoverAnimated:YES];
		self.popController = nil;
	}
}*/

-(void)viewDidUnload
{
    _loadFooterView = nil;
    [self.popController dismissPopoverAnimated:NO];
	self.popController = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [_tableView removeObserver:self forKeyPath:@"contentSize"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _headerView = [[SectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    _headerView.delegate = self;
    
    _sortDic = [[NSMutableDictionary alloc] init];
    [_sortDic setObject:@"expectedYield" forKey:@"预期收益"];
    [_sortDic setObject:@"mgrPeriod" forKey:@"委托期限"];
    [_sortDic setObject:@"prodType" forKey:@"收益类型"];
    [_sortDic setObject:@"startMoney" forKey:@"起售金额"];
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"toolbar.jpg"] forBarMetrics:UIBarMetricsDefault];
    }
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"高级筛选" style:UIBarButtonItemStyleBordered target:self action:@selector(getSearch)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [self.navigationItem setTitle:@"产品浏览"];
    [self.navigationItem setRightBarButtonItem:leftItem];
 
        
    self.pageIndex = 0;
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-90) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    [_tableView setBackgroundColor:bk];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorColor = [UIColor blackColor];
    
    [self.view addSubview:_tableView];
    
    if (_refreshTableView == nil) {
        EGORefreshTableHeaderView *refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        refreshView.delegate = self;
        [self.tableView addSubview:refreshView];
        _refreshTableView = refreshView;
    }
    
    _dataArray = [[NSMutableArray alloc] init];
    
    _backdiect = [[NSMutableDictionary alloc] init];
	// Do any additional setup after loading the view.
    
    if (_loadFooterView == nil) {
		
		_loadFooterView = [[LoadMoreFooterView alloc] initWithFrame: CGRectZero];
		[self.tableView addSubview:_loadFooterView];
	}
    
    [self packageRequest];
    
}

- (void)packageRequest
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W102"];
    if (self.type == ServerTypeRefresh) {
        self.pageIndex = 0;
    }
    NSDictionary *body = [self PackageBody:self.pageIndex];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
        
    //发送报文
    [self getTableData: requestJson];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"contentSize"])
    {
        if ([_dataArray count] >= AMOUNT_MIN.intValue) {
            _loadFooterView.frame = CGRectMake(0.0f, self.tableView.contentSize.height, 320, 250);
        }else{
            _loadFooterView.frame = CGRectZero;
        }
    }
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryProdInfo"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)requestCallBack:(NSDictionary *)dic
{
    NSObject *body = dic[@"body"];
    NSLog(@"%@",[body class]);
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"products"] != nil)
    {
        switch (_type) {
            case ServerTypeRefresh:
                self.dataArray = [(NSDictionary *)body objectForKey:@"products"];
                break;
            case ServerTypeLoadMore:
                [self.dataArray addObjectsFromArray:[(NSDictionary *)body objectForKey:@"products"]];
                break;
            default:
                break;
        }
    }
    
    [self doneLoadingTableViewData];
    
    [self.tableView reloadData];
}

//每次组报文需要实现类似组body的方法
- (NSDictionary *)PackageBody:(int)index
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"pageIndex"] = [NSString stringWithFormat:@"%d",index];
    dic[@"pageSize"] = AMOUNT_MIN;
    dic[@"sortBy"] = [self getConditionFromSort];
    return dic;
}

//从sortdic中取出筛选条件
- (NSString *)getConditionFromSort
{
    NSMutableString *condition = [NSMutableString stringWithString:@""];
    [condition appendString:(NSString *)[_sortDic objectForKey:@"预期收益"]];
    [condition appendString:[NSString stringWithFormat:@",%@",(NSString *)[_sortDic objectForKey:@"委托期限"]]];
    [condition appendString:[NSString stringWithFormat:@",%@",(NSString *)[_sortDic objectForKey:@"收益类型"]]];
    [condition appendString:[NSString stringWithFormat:@",%@",(NSString *)[_sortDic objectForKey:@"起售金额"]]];
    return condition;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)clickOnHeader:(NSString *)btn sort:(NSString *)sortStr
{
    if ([btn isEqualToString:@"预期收益"]) {
        if ([sortStr isEqualToString:@"incs"]) {
            [_sortDic setObject:@"expectedYield" forKey:@"预期收益"];
        }else if ([sortStr isEqualToString:@"desc"]){
            [_sortDic setObject:@"expectedYield desc" forKey:@"预期收益"];
        }
    }else if ([btn isEqualToString:@"委托期限"]){
        if ([sortStr isEqualToString:@"incs"]) {
            [_sortDic setObject:@"mgrPeriod" forKey:@"委托期限"];
        }else if ([sortStr isEqualToString:@"desc"]){
            [_sortDic setObject:@"mgrPeriod desc" forKey:@"委托期限"];
        }
    }else if ([btn isEqualToString:@"收益类型"]){
        if ([sortStr isEqualToString:@"incs"]) {
            [_sortDic setObject:@"prodType" forKey:@"收益类型"];
        }else if ([sortStr isEqualToString:@"desc"]){
            [_sortDic setObject:@"prodType desc" forKey:@"收益类型"];
        }
    }else if ([btn isEqualToString:@"起售金额"]){
        if ([sortStr isEqualToString:@"incs"]) {
            [_sortDic setObject:@"startMoney" forKey:@"起售金额"];
        }else if ([sortStr isEqualToString:@"desc"]){
            [_sortDic setObject:@"startMoney desc" forKey:@"起售金额"];
        }
    }
    _type = ServerTypeRefresh;
    [self packageRequest];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _headerView;;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!_headerView) {
        return 0;
    }
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_dataArray count] >= AMOUNT_MIN.intValue) {
        _loadFooterView.delegate = self;
        _loadFooterView.arrowImage.hidden = NO;
    }else{
        _loadFooterView.delegate = nil;
        _loadFooterView.arrowImage.hidden = YES;
    }
    return [_dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"cell at %d",indexPath.row];
    ProductListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 78, cell.frame.size.width, 2)];
//        lineImageView.image = [UIImage imageNamed:@"line-gray.png"];
//        [cell.contentView addSubview:lineImageView];
        
    }
    NSDictionary *dic = [_dataArray objectAtIndex:[indexPath row]];
    
    NSString* backname = dic[@"bankName"];
    NSString* backicon = dic[@"imageUrl"];
    
    if([self checkExist:backname] == false)
    {
        [self.backdiect setValue:backicon forKey:backname];
    }
    
    [cell drawCell:dic];
    return cell;
}

-(BOOL)checkExist:(NSString*)backname
{
    for (NSString* key in [self.backdiect allKeys])
    {
        if([backname compare:key] == 0)
        {
            return true;
        }
    }

    return false;
}

-(void)viewWillDisappear:(BOOL)animated {
    
    //[self resignFirstResponder];
    [self setHidesBottomBarWhenPushed:NO];
    [super viewWillDisappear:animated];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.toolbarHidden = YES;
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate showTabBarWithoutAnimation:aController];
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:animated];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [_dataArray objectAtIndex:[indexPath row]];
    NearbyDetailViewController *aController = [[NearbyDetailViewController alloc] init];
    aController.proId = [dic objectForKey:@"prodId"];
    [self.navigationController pushViewController:aController animated:YES];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	[self packageRequest];
    
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
    switch (_type) {
        case ServerTypeRefresh:
            [_refreshTableView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
            break;
        case ServerTypeLoadMore:
            [_loadFooterView loadMoreScrollViewDataSourceDidFinishedLoading:self.tableView];
            break;
        default:
            break;
    }	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
    _type = ServerTypeRefresh;
    [self reloadTableViewDataSource];
}

-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
    return _reloading;
}

-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    self.currentOffsetPoint = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[_refreshTableView egoRefreshScrollViewDidScroll:scrollView];
    //CGPoint pt = scrollView.contentOffset;
    //if (self.currentOffsetPoint.y < pt.y) {
    if (_loadFooterView.delegate == nil) {
        return;
    }
    [_loadFooterView loadMoreScrollViewDidScroll:scrollView];
	//}
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshTableView egoRefreshScrollViewDidEndDragging:scrollView];
    //CGPoint pt = scrollView.contentOffset;
    //if (self.currentOffsetPoint.y < pt.y) {
    if (_loadFooterView.delegate == nil) {
        return;
    }
    [_loadFooterView loadMoreScrollViewDidEndDragging:scrollView];
	//}
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)loadMoreTableFooterDidTriggerRefresh:(LoadMoreFooterView *)view{
	_pageIndex++;
    _type = ServerTypeLoadMore;
	[self reloadTableViewDataSource];
    
    
	//[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:4.0];
	
}

- (BOOL)loadMoreTableFooterDataSourceIsLoading:(LoadMoreFooterView *)view{
	
	return _reloading; // should return if data source model is reloading
	
}

#pragma mark -
#pragma mark WEPopoverControllerDelegate implementation

- (void)popoverControllerDidDismissPopover:(WEPopoverController *)thePopoverController {
	//Safe to release the popover here
	self.popController = nil;
}

- (BOOL)popoverControllerShouldDismissPopover:(WEPopoverController *)thePopoverController {
	//The popover is automatically dismissed if you click outside it, unless you return NO here
	return YES;
}


@end
